package com.ldodds.ot.id;

/**
 * Implementation of the {@link IdentifierRewriter} interface that is 
 * capable of rewriting URIs using a common base URI.
 * 
 * @author Leigh Dodds
 */
public class SimpleIdentifierRewriter implements IdentifierRewriter {

	private String baseURI;

	/**
	 * Create a rewriter capable of rewriting URIs using the provided base 
	 * URI. This will be added as a prefix to relative URIs and stripped from 
	 * absolute URIs.
	 * 
	 * @param baseURI the base uri to use
	 */
	public SimpleIdentifierRewriter(String baseURI) {
		this.baseURI = baseURI;
		if (baseURI == null) {
			throw new IllegalArgumentException("baseURI cannot be null");
		}
		if ( baseURI.endsWith("/") ) {
			this.baseURI = baseURI.substring(0, baseURI.length()-1);
		}
	}
	
	/**
	 * Convert the provided relative URI into an absolute URI by adding the 
	 * base URL as a prefix.
	 */
	public String getIdentifier(String webIdentifier) {
		return baseURI + webIdentifier;
	}

	/**
	 * Convert the absolute URI into a relative URI by removing the base URI.
	 * If the identifier does not include the prefix then it is returned unchanged.
	 */
	public String getWebIdentifier(String identifier) {
		return identifier.replace(baseURI, "");
	}

}
